// START WRAPPER: The YUI.add wrapper is added by the build system, when you use YUI Builder to build your component from the raw source in this file
 YUI.add("article-dialog", function(Y) {

    /* Any frequently used shortcuts, strings and constants */
    var Lang = Y.Lang;

    /* ArticleDialog class constructor */
    function ArticleDialog(config) {
        ArticleDialog.superclass.constructor.apply(this, arguments);
    }

    /* 
     * Required NAME static field, to identify the Widget class and 
     * used as an event prefix, to generate class names etc. (set to the 
     * class name in camel case). 
     */
    ArticleDialog.NAME = "ArticleDialog";

    /*
     * The attribute configuration for the widget. This defines the core user facing state of the widget
     */
    ArticleDialog.ATTRS = {
    	article : {
    		value : null
    	},
    	relationModelId : {
    		value : -1
    	},
    	siteId : {
    		value : -1
    	},
        attrA : {
            value: "A"                     // The default value for attrA, used if the user does not set a value during construction.

            /*
            , valueFn: "_defAttrAVal"      // Can be used as a substitute for "value", when you need access to "this" to set the default value.
             
            , setter: "_setAttrA"          // Used to normalize attrA's value while during set. Refers to a prototype method, to make customization easier
            , getter: "_getAttrA"          // Used to normalize attrA's value while during get. Refers to a prototype method, to make customization easier
            , validator: "_validateAttrA"  // Used to validate attrA's value before updating it. Refers to a prototype method, to make customization easier

            , readOnly: true               // Cannot be set by the end user. Can be set by the component developer at any time, using _set
            , writeOnce: true              // Can only be set once by the end user (usually during construction). Can be set by the component developer at any time, using _set
            
            , lazyAdd: false               // Add (configure) the attribute during initialization. 
            
                                           // You only need to set lazyAdd to false if your attribute is
                                           // setting some other state in your setter which needs to be set during initialization 
                                           // (not generally recommended - the setter should be used for normalization. 
                                           // You should use listeners to update alternate state). 

            , broadcast: 1                 // Whether the attribute change event should be broadcast or not.
            */
        }
        
        // ... attrB, attrC, attrD ... attribute configurations. 

        // Can also include attributes for the super class if you want to override or add configuration parameters
    };

    /* 
     * The HTML_PARSER static constant is used if the Widget supports progressive enhancement, and is
     * used to populate the configuration for the ArticleDialog instance from markup already on the page.
     */
    ArticleDialog.HTML_PARSER = {

        attrA: function (srcNode) {
            // If progressive enhancement is to be supported, return the value of "attrA" based on the contents of the srcNode
        }

    };
    
    ArticleDialog.ARTILE_TEMPLATE = '<li id="m3958-article-{aid}" class="m3958-article-list-item"><span class="article-list-title">{title}</span><span class="article-list-publishedAt">{publishedAt}</span></li>';

    /* Templates for any markup the widget uses. Usually includes {} tokens, which are replaced through Y.substitute */
    ArticleDialog.MYNODE_TEMPLATE = "<div id={mynodeid}></div>";

    /* ArticleDialog extends the base Widget class */
    Y.extend(ArticleDialog, Y.Panel, {

        initializer: function() {
            /*
             * initializer is part of the lifecycle introduced by 
             * the Base class. It is invoked during construction,
             * and can be used to setup instance specific state or publish events which
             * require special configuration (if they don't need custom configuration, 
             * events are published lazily only if there are subscribers).
             *
             * It does not need to invoke the superclass initializer. 
             * init() will call initializer() for all classes in the hierarchy.
             */
        	
        	var contentBox = this.get('contentBox'),
        		wid = (this.get('width') - 40) + 'px',
        		outThis = this;
        	
        	this._formNode = contentBox.one('form');
        	this._titleNode = contentBox.one('#article-dialog-title');
        	this._contentNode = contentBox.one('#article-dialog-content');
        	this._answerNode = contentBox.one('#article-dialog-answer');
        	this._captchaNode = contentBox.one('#article-dialog-captcha');
        	
        	this._titleNode.setStyle('width',wid);
        	this._contentNode.setStyle('width',wid);
        	this._contentNode.setStyle('height','100px');
        	
        	this.addButton({
        	    value  : '发表',
        	    section: Y.WidgetStdMod.FOOTER,
        	    action : function (e) {
        	        e.preventDefault();
        	        outThis._startIO();
        	    }
        	});
        	
             this.publish("myEvent", {
                defaultFn: this._defMyEventFn,
                bubbles:false
             });
        },

        destructor : function() {
            /*
             * destructor is part of the lifecycle introduced by 
             * the Widget class. It is invoked during destruction,
             * and can be used to cleanup instance specific state.
             *
             * Anything under the boundingBox will be cleaned up by the Widget base class
             * We only need to clean up nodes/events attached outside of the bounding Box
             *
             * It does not need to invoke the superclass destructor. 
             * destroy() will call initializer() for all classes in the hierarchy.
             */
        },

        renderUI : function() {
            /*
             * renderUI is part of the lifecycle introduced by the
             * Widget class. Widget's renderer method invokes:
             *
             *     renderUI()
             *     bindUI()
             *     syncUI()
             *
             * renderUI is intended to be used by the Widget subclass
             * to create or insert new elements into the DOM. 
             */
        	this._captchaNode.set('src','/simpleImg?' + Math.random());
             // this._mynode = Node.create(Y.substitute(ArticleDialog.MYNODE_TEMPLATE, {mynodeid: this.get("id") + "_mynode"})); 
        },

        bindUI : function() {
            /*
             * bindUI is intended to be used by the Widget subclass 
             * to bind any event listeners which will drive the Widget UI.
             * 
             * It will generally bind event listeners for attribute change
             * events, to update the state of the rendered UI in response 
             * to attribute value changes, and also attach any DOM events,
             * to activate the UI.
             */
        	
        	this._captchaNode.on('click',function(e){
        		this.set('src','/simpleImg?' + Math.random());
        	});
//        	var outThis = this;
//        	this.after('articleChange',this._afterArticleChange);
//        	this.after('sectionChange',this._afterSectionChange);
//        	if(this.get('section')){
//                this.get('section').on('articleFetched',function(e){
//                	outThis.set('articles',e.articles);
//                });
//        	}
        },

        syncUI : function() {
            /*
             * syncUI is intended to be used by the Widget subclass to
             * update the UI to reflect the initial state of the widget,
             * after renderUI. From there, the event listeners we bound above
             * will take over.
             */
//        	var article = this.get('article'),
//        		outThis = this;
//        	
//        	if(article){
//        		this.setStdModContent(Y.WidgetStdMod.HEADER,article.gett('title'),Y.WidgetStdMod.REPLACE);
//        		outThis.setStdModContent(Y.WidgetStdMod.BODY,article.gett('content'),Y.WidgetStdMod.REPLACE);
//            	this.setStdModContent(Y.WidgetStdMod.FOOTER,'');
//        	}
            // this._uiSetAttrA(this.get("attrA"));
        },

        // Beyond this point is the ArticleDialog specific application and rendering logic
        
//        _attachment_json	{"contentImgs":[], "attachments":[]}
//        _componentId	isc_DynamicForm_4
//        _dataSource	articleDS
//        _modelName	com.m3958.firstgwt.server.model.Article
//        _oldValues	{}
//        _operationType	add
//        _relationModelId	75014
//        _tz	Asia/Shanghai
//        commentLevel	0
//        content	学习下<br />
//        defaultSectionId	75014
//        isc_dataFormat	json
//        isc_metaDataPrefix	_
//        protectLevel	
//        siteId	74067
//        title	学习学习
        _resetForm : function(){
        	this._answerNode.set('value','');
        	this._contentNode.set('value','');
        	this._titleNode.set('value','');
        },
        _io_success : function(id, o, args){
        	var rr = Y.JSON.parse(o.responseText),
        		r = rr.response;
        	if(r.status === 0 && r.data && r.data.length == 1){
        		Y.M3958.DAYAN.messagePanel.info('我们已收到您的反馈，会尽快处理，谢谢您的参与！');
        		this._resetForm();
        	}else if(r.status != 0 && r.data && r.data.length == 1){
        		var ed = r.data[0];
        		if(ed.code == -11){
        			Y.M3958.DAYAN.messagePanel.warn('验证码错误，请重新输入！');
        		}else{
        			Y.M3958.DAYAN.messagePanel.warn(ed.message);
        		}
        	}else{
        		Y.M3958.DAYAN.messagePanel.warn('服务器没有接受您的文章，请联系管理员！');
        	}
        },
        
        _io_failure : function(id, o, args){
        	Y.M3958.DAYAN.messagePanel.warn('服务器没有接受您的文章，请联系管理员！');
        },
        
        /* Attribute state supporting methods (see attribute config above) */
        _getTransCfg : function(){
        	var data = {'_modelName':'com.m3958.firstgwt.server.model.Article',
        				'_operationType':'add',
        				'_relationModelId':this.get('relationModelId'),
        				'defaultSectionId':this.get('relationModelId'),
        				'siteId':this.get('siteId')};
        	data.title = this._titleNode.get('value');
        	data.content = this._contentNode.get('value');
        	data.answer = this._answerNode.get('value');
            return {
            		method :'POST',
            		data : data,
                    on: {
                        start: this._io_start,
                        complete: this._io_complete,
                        success: this._io_success,
                        failure: this._io_failure,
                        end: this._io_end
                    },
                    context: this,
                    arguments: {}
                };
        },
        _startIO : function(){
        	var cfg = this._getTransCfg();
        	if(!cfg.data.title){
        		Y.M3958.DAYAN.messagePanel.warn('请输入标题！');
        		return;
        	}else if(!cfg.data.content){
        		Y.M3958.DAYAN.messagePanel.warn('请输入内容！');
        		return;
        	}else if(!cfg.data.answer || cfg.data.answer.length != 5){
        		Y.M3958.DAYAN.messagePanel.warn('请输入5位验证码！');
        		return;
        	}
        	Y.io('/jqfprocessor?', cfg);
        },
        
        refreshCaptch : function(){
        	this._captchaNode.set('src','/simpleImg?' + Math.random());
        },
        
        _defAttrAVal : function() {
            // this.get("id") + "foo";
        },

        _setAttrA : function(attrVal, attrName) {
            // return attrVal.toUpperCase();
        },

        _getAttrA : function(attrVal, attrName) {
            // return attrVal.toUpperCase();
        },

        _validateAttrA : function(attrVal, attrName) {
            // return Lang.isString(attrVal);
        },

        /* Listeners, UI update methods */

        _afterAttrAChange : function(e) {
            /* Listens for changes in state, and asks for a UI update (controller). */

            // this._uiSetAttrA(e.newVal);
        },

        _uiSetAttrA : function(val) {
            /* Update the state of attrA in the UI (view) */

            // this._mynode.set("innerHTML", val);
        },

        _defMyEventFn : function(e) {
            // The default behavior for the "myEvent" event.
        }
    });

    Y.namespace("M3958").ArticleDialog = ArticleDialog;

 }, "0.0.1", {requires:["panel",'dd-plugin',"substitute","array-extras","io-base","json","querystring-stringify-simple"]});
// END WRAPPER